import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import { Message } from 'element-ui'
import store from '@/store'
import {router} from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000, // request timeout
  headers:{
    post:{
      'Content-Type':'application/json'
    }
  }
})

service.interceptors.request.use(
  config => {
    if (store.getters.GET_USERDATA.token) {
      config.headers['X-Token'] = store.getters.GET_USERDATA.token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.msg == 'nologin' || res.msg == 'expired') {
      store.dispatch('logout')
      router.push('/login?redirect=')
      Message({
        message: 'token过期，请重新登录',
        type: 'error',
        duration: 3 * 1000
      })
      return
    }
    if (res.code == -1 && !response.config.silent) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return res
  },
  error => {
    console.log(4,error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
